import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'app_localizations.dart';
import 'language_view_model.dart';
import 'home_page.dart';

void main() {
  runApp(
    const LanguageProvider(
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<LanguageViewModel>(
      builder: (context, languageViewModel, child) {
        return MaterialApp(
          title: 'Multilingual Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          darkTheme: ThemeData.dark(),
          locale: languageViewModel.currentLocale,
          supportedLocales: const [
            Locale('en', ''), // English
            Locale('zh', ''), // Chinese
            Locale('ja', ''), // Japanese
          ],
          localizationsDelegates: const [
            AppLocalizations.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          localeResolutionCallback: (locale, supportedLocales) {
            // 检查设备语言是否在支持的列表中
            for (var supportedLocale in supportedLocales) {
              if (supportedLocale.languageCode == locale?.languageCode) {
                return supportedLocale;
              }
            }
            // 如果不支持，使用默认语言
            return const Locale('en', '');
          },
          home: const HomePage(),
        );
      },
    );
  }
}
